/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alipay.api.domain.RecordDetail;
import com.baomidou.mybatisplus.core.metadata.IPage;
import me.zhengjie.modules.system.domain.Dict;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.domain.Shift;
import me.zhengjie.modules.system.mapper.DictDetailMapper;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.system.service.ShiftService;
import me.zhengjie.modules.system.domain.vo.ShiftQueryCriteria;
import me.zhengjie.modules.system.mapper.ShiftMapper;
import me.zhengjie.utils.Travelsal;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;

import java.sql.Array;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import me.zhengjie.utils.PageResult;

/**
* @description 服务实现
* @author pysduck
* @date 2023-12-01
**/
@Service
@RequiredArgsConstructor
public class ShiftServiceImpl extends ServiceImpl<ShiftMapper, Shift> implements ShiftService {

    private final ShiftMapper shiftMapper;
    private final DictDetailMapper dictDetailMapper;

    @Override
    public PageResult<Shift> queryAll(ShiftQueryCriteria criteria, Page<Object> page){
        IPage<Shift> all = shiftMapper.findAll(criteria, page);
        List<Shift> records = all.getRecords();
        Map<String, List<Shift>> collect = records.stream().collect(Collectors.groupingBy(Shift::getShift));
        records.clear();
        int i=0;
        for (Map.Entry<String, List<Shift>> entry:collect.entrySet()) {
            i++;
            Shift shift = new Shift();
            List<Shift> shiftChildList = new ArrayList<>();
            Shift shifts = entry.getValue().get(0);
            shift.setId((long) i);
            shift.setShift(shifts.getShift());
            shift.setShiftName(shifts.getShiftName());
            shift.setFacility(shifts.getFacility());
            shift.setStatus(shifts.getStatus());
            for (Shift record:entry.getValue()) {
                record.setStatus(null);
                shiftChildList.add(record);
            }
            shift.setChildren(shiftChildList);
            records.add(shift);
        }
        all.setTotal(records.size());
        return PageUtil.toPage(all);
    }

    @Override
    public List<Shift> queryAll(ShiftQueryCriteria criteria){
        List<Shift> all = shiftMapper.findAll(criteria);
        Map<String, List<Shift>> collect = all.stream().collect(Collectors.groupingBy(Shift::getShift));
        all.clear();
        for (Map.Entry<String, List<Shift>> entry:collect.entrySet()) {
            Shift shift = new Shift();
            List<Shift> shiftChildList = new ArrayList<>();
            Shift shifts = entry.getValue().get(0);
            shift.setShift(shifts.getShift());
            shift.setShiftName(shifts.getShiftName());
            shift.setFacility(shifts.getFacility());
            shift.setStatus(shifts.getStatus());
            for (Shift record:entry.getValue()) {
                shiftChildList.add(record);
            }
            shift.setChildren(shiftChildList);
            all.add(shift);
        }
        return all;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Shift resources) {
        save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Shift resources) {
        Shift shift = getById(resources.getId());
        if(shift == null){
            save(resources);
        }else {
            shift.copy(resources);
            saveOrUpdate(shift);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<Shift> all, HttpServletResponse response) throws IOException {
         List<Map<String, Object>> list = new ArrayList<>();
         List<DictDetail> hoursType = dictDetailMapper.findByDictName("hours_type");
         Map<String,String> hoursMap = new HashMap<>();
         hoursType.forEach( o -> {
             hoursMap.put(o.getValue(),o.getLabel());
         });
        for (Shift shift : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("车间", shift.getFacility());
            map.put("班次", shift.getShift());
            map.put("班次名称", shift.getShiftName());
            shift.getChildren().forEach(Travelsal.consumerWithIndex((shift1,index) ->  {
                map.put("工时类型"+index, hoursMap.get(shift1.getHoursType()));
                map.put("开始时间"+index, shift1.getStartTime().toString());
                map.put("结束时间"+index, shift1.getEndTime().toString());
                map.put("是否计入工时"+index, shift1.getIsBillable()==0?"否":"是");
            }));
            map.put("状态", shift.getStatus()==0?"停用":"启用");
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}